<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form" style="margin-bottom: 10px">
          <el-form-item>
            <el-button class="" type="warning" v-html="exportBtnText" @click="batchExport()">备份</el-button>
            <el-button class="" type="success" @click="batchOptimize(selection)">优化表</el-button>
            <el-button class="" type="success" @click="batchRepair(selection)">修复表</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :height="height+60" style="width: 100%" border row-key="id" @selection-change="tableSelect">
      <el-table-column type="selection" min-width="40" align="center"/>
      <el-table-column prop="numbers" label="序号" min-width="80" align="center"/>
      <el-table-column prop="Name" label="表名" min-width="200" align="center" show-overflow-tooltip/>
      <el-table-column prop="Rows" label="数据量" min-width="100" align="center"/>
      <el-table-column prop="Data_length" label="数据大小" min-width="100" align="center"/>
      <el-table-column prop="Collation" label="编码" min-width="160" align="center"/>
      <el-table-column prop="Create_time" label="创建时间" min-width="160" align="center"/>
      <el-table-column prop="Comment" label="说明" min-width="160" align="center" show-overflow-tooltip/>
      <el-table-column prop="status" label="状态" min-width="130" align="center">
        <template slot-scope="{row}">
          <el-tag type="info" :class="'btn--'+row.Name">未备份</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" align="center">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="optimize([row])">优化表</el-button>
          <el-button type="" size="mini" @click="repair([row])">修复表</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import {exportList, doExport, optimize, repair} from '@/api/admin/database'

export default {
  name: 'AdminDatabaseExport',
  components: {},
  data() {
    return {
      name: '数据库表',
      height: 680,
      loading: false,
      datas: [],
      query: {},
      model: {
        numbers: '',
        Name: '',
        Rows: '',
        Data_length: '',
        Collation: '',
        Create_time: '',
        Comment: ''
      },

      selection: [], // 选中项
      selectedNames: [], // 选中项的name集合
      exportBtnText: '<i class="el-icon-video-play"/>备份',
      defaultStatusText: '<el-tag type="info">未备份</el-tag>'
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      exportList(this.query).then(res => {
        this.datas = res.data.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 备份
    doExport(row) {
      var title = '备份' + this.name
      var message = '确定要备份选中的 <span style="color:red">' + row.length + ' </span> 条' + this.name + '数据吗？'
      var tables = this.selectedNames
      this.$confirm(message, title, {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在发送备份请求...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        doExport({
          tables: tables
        }).then(res => {
          loading.setText(res.data.info + '开始备份，请不要关闭本页面！');
          this.backup(res.data, row, loading)
        }).catch(() => {
          loading.close()
        })
        window.onbeforeunload = function () {
          return "正在备份数据库，请不要关闭！"
        }
      }).catch(() => {
      })
    },
    // 优化表
    optimize(row) {
      var title = '优化' + this.name
      var message = '确定要优化选中的 <span style="color:red">' + row.length + ' </span> 条' + this.name + '数据吗？'
      var tables = this.selectedNames
      if (row.length === 1) {
        title = '表名：' + row[0].Name
        message = '确定要优化表名: <span style="color:red">' + row[0].Name + ' </span> 这条数据吗？'
        tables = [row[0].Name]
      }
      this.$confirm(message, title, {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在优化数据库表，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        optimize({
          tables: tables
        }).then(res => {
          loading.close();
          if (res.code == 200) {
            this.$message.success(res.msg)
          } else {
            this.$message.info(res.msg)
          }
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    // 修复表
    repair(row) {
      var title = '修复' + this.name
      var message = '确定要修复选中的 <span style="color:red">' + row.length + ' </span> 条' + this.name + '数据吗？'
      var tables = this.selectedNames
      if (row.length === 1) {
        title = '表名：' + row[0].Name
        message = '确定要修复表名: <span style="color:red">' + row[0].Name + ' </span> 这条数据吗？'
        tables = [row[0].Name]
      }
      this.$confirm(message, title, {
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在修复数据库表，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        repair({
          tables: tables
        }).then(res => {
          loading.close()
          if (res.code == 200) {
            this.$message.success(res.msg)
          } else {
            this.$message.info(res.msg)
          }
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
    },

    // 全选操作 -- table 表头
    tableSelect(selection) {
      this.selection = selection
      let names = []
      for (let row of this.selection) {
        names.push(row.Name)
      }
      this.selectedNames = names
    },
    // 未选择提示信息
    unSelectedMsg(message = '') {
      this.$alert(message || '请选择需要操作的' + this.name, '提示', {
        confirmButtonText: '确定', callback: action => {
        }
      })
    },
    // 批量备份表
    batchExport() {
      if (!this.selection.length) {
        this.unSelectedMsg()
      } else {
        this.doExport(this.selection)
      }
    },
    // 批量优化表
    batchOptimize(row) {
      if (!this.selection.length) {
        this.unSelectedMsg()
      } else {
        this.optimize(row)
      }
    },
    // 批量修复表
    batchRepair(row) {
      if (!this.selection.length) {
        this.unSelectedMsg()
      } else {
        this.repair(row)
      }
    },

    // 备份
    backup(data, row, loading) {
      // 开始备份
      if (data.status == 1) {
        document.getElementsByClassName('btn--' + data.tab.name)[0].innerHTML = "开始备份...(0%)"
        document.getElementsByClassName('btn--' + data.tab.name)[0].classList.remove('el-tag--success')
        document.getElementsByClassName('btn--' + data.tab.name)[0].classList.add('el-tag--info')
        doExport({
          id: data.tab.id,
          start: data.tab.start
        }).then(res2 => {
          document.getElementsByClassName('btn--' + data.tab.name)[0].innerHTML = res2.data.info
          document.getElementsByClassName('btn--' + data.tab.name)[0].classList.remove('el-tag--info')
          document.getElementsByClassName('btn--' + data.tab.name)[0].classList.add('el-tag--success')
          if (res2.data.tab) {
            this.backup(res2.data, row, loading)
          } else {
            this.exportBtnText = '备份完成，点击重新备份'
            loading.close()
            window.onbeforeunload = function () {
              return null
            }
          }
        }).catch(() => {
          loading.close()
        })
      }
    }
  }
}
</script>
